package cn.wolfcode.web.modules.custinfo.controller;

import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.CityUtils;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.linkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.linkman.service.ITbCustLinkmanService;
import cn.wolfcode.web.modules.log.LogModules;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;
import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import link.ahsj.core.exception.AppServerException;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author MAOWEI
 * @since 2023-07-31
 */
@Controller
@RequestMapping("custinfo")
public class TbCustomerController extends BaseController {

    @Autowired
    private ITbCustomerService entityService;

    @Autowired
    private ITbCustLinkmanService custLinkmanService;

    private static final String LogModule = "TbCustomer";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {
        mv.addObject("citys", CityUtils.citys);
        mv.setViewName("cust/custinfo/list");
        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('cust:custinfo:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        mv.addObject("citys", CityUtils.citys);
        mv.setViewName("cust/custinfo/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('cust:custinfo:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        mv.setViewName("cust/custinfo/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        mv.addObject("citys", CityUtils.citys);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('cust:custinfo:list')")
    public ResponseEntity page(LayuiPage layuiPage, String parameterName, String provinceId) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());
        LambdaQueryWrapper<TbCustomer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(parameterName), TbCustomer::getCustomerName, parameterName)
                .or()
                .like(StringUtils.isNotBlank(parameterName), TbCustomer::getLegalLeader, parameterName)
                .or()
                .eq(StringUtils.isNotBlank(provinceId), TbCustomer::getProvince, provinceId);
        IPage iPage = entityService.page(page, queryWrapper);
        List<TbCustomer> tbCustomerList = iPage.getRecords();
        for (TbCustomer tbCustomer : tbCustomerList) {
            tbCustomer.setProvinceName(CityUtils.getCityValue(tbCustomer.getProvince()));
        }
        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(iPage));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module = LogModule)
    @PreAuthorize("hasAuthority('cust:custinfo:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbCustomer entity) {
        // 查询数据库中是否存在该企业名称
        LambdaQueryWrapper<TbCustomer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbCustomer::getCustomerName, entity.getCustomerName());
        TbCustomer tbCustomer = entityService.getOne(queryWrapper);
        if (tbCustomer != null) {
            throw new AppServerException("该客户名称已存在");
        }
        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('cust:custinfo:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbCustomer entity) {
        // 查询数据库中是否存在该企业名称
        LambdaQueryWrapper<TbCustomer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbCustomer::getCustomerName, entity.getCustomerName())
                .ne(TbCustomer::getId, entity.getId());
        TbCustomer tbCustomer = entityService.getOne(queryWrapper);
        if (tbCustomer != null) {
            throw new AppServerException("该客户名称已存在");
        }
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('cust:custinfo:delete')")
    @Transactional
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        LambdaQueryWrapper<TbCustLinkman> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbCustLinkman::getCustId, id);
        custLinkmanService.remove(queryWrapper);
        return ResponseEntity.ok(ApiModel.ok());
    }

}
